<template>
  <el-dialog
    :model-value="visible"
    :title="mode === 'create' ? '添加用户' : '编辑用户'"
    width="700px"
    :close-on-click-modal="false"
    @update:model-value="$emit('update:visible', $event)"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="form.username"
              placeholder="请输入用户名"
              maxlength="20"
              show-word-limit
              :disabled="mode === 'edit'"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="form.name"
              placeholder="请输入姓名"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="form.email"
              placeholder="请输入邮箱"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="form.phone"
              placeholder="请输入手机号"
              maxlength="11"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item v-if="mode === 'create'" label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
          maxlength="20"
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
              <el-option label="管理员" value="admin" />
              <el-option label="经理" value="manager" />
              <el-option label="客服" value="agent" />
              <el-option label="客户" value="customer" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
              <el-option label="激活" value="active" />
              <el-option label="禁用" value="inactive" />
              <el-option label="暂停" value="suspended" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="部门" prop="department">
            <el-input
              v-model="form.department"
              placeholder="请输入部门"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="职位" prop="position">
            <el-input
              v-model="form.position"
              placeholder="请输入职位"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="个人简介" prop="bio">
        <el-input
          v-model="form.bio"
          type="textarea"
          :rows="3"
          placeholder="请输入个人简介（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="头像" prop="avatar">
        <el-upload
          ref="uploadRef"
          :file-list="fileList"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-change="handleFileChange"
          :on-remove="handleFileRemove"
          accept="image/*"
        >
          <el-button type="primary">
            <el-icon><Upload /></el-icon>
            选择头像
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              支持 jpg/png/gif 格式，且不超过 2MB
            </div>
          </template>
        </el-upload>
      </el-form-item>

      <!-- 权限设置 -->
      <el-form-item label="权限设置" prop="permissions">
        <div class="permissions-section">
          <div class="permission-group">
            <h4>工单权限</h4>
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="ticket:read">查看工单</el-checkbox>
              <el-checkbox value="ticket:create">创建工单</el-checkbox>
              <el-checkbox value="ticket:update">更新工单</el-checkbox>
              <el-checkbox value="ticket:delete">删除工单</el-checkbox>
              <el-checkbox value="ticket:assign">指派工单</el-checkbox>
            </el-checkbox-group>
          </div>
          
          <div class="permission-group">
            <h4>用户管理权限</h4>
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="user:manage">用户管理</el-checkbox>
            </el-checkbox-group>
          </div>
          
          <div class="permission-group">
            <h4>系统权限</h4>
            <el-checkbox-group v-model="form.permissions">
              <el-checkbox value="system:config">系统配置</el-checkbox>
              <el-checkbox value="report:view">报表查看</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </el-form-item>

      <!-- 通知设置 -->
      <el-form-item label="通知设置" prop="notifications">
        <div class="notification-settings">
          <el-checkbox-group v-model="form.notifications">
            <el-checkbox value="email">邮件通知</el-checkbox>
            <el-checkbox value="sms">短信通知</el-checkbox>
            <el-checkbox value="system">系统通知</el-checkbox>
            <el-checkbox value="push">推送通知</el-checkbox>
          </el-checkbox-group>
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">
          {{ submitting ? '保存中...' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch, computed } from 'vue'
import { useUserStore } from '../store/user'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserFormDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: null
    },
    mode: {
      type: String,
      default: 'create',
      validator: (value) => ['create', 'edit'].includes(value)
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const userStore = useUserStore()
    const formRef = ref()
    const uploadRef = ref()
    const submitting = ref(false)
    const fileList = ref([])

    // 表单数据
    const form = reactive({
      username: '',
      name: '',
      email: '',
      phone: '',
      password: '',
      role: 'agent',
      status: 'active',
      department: '',
      position: '',
      bio: '',
      avatar: '',
      permissions: [],
      notifications: ['system']
    })

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
        { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
      ],
      name: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
        { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }

    // 监听user变化，用于编辑模式
    watch(() => props.user, (newUser) => {
      if (newUser && props.mode === 'edit') {
        Object.assign(form, {
          username: newUser.username || '',
          name: newUser.name || '',
          email: newUser.email || '',
          phone: newUser.phone || '',
          password: '', // 编辑时不显示密码
          role: newUser.role || 'agent',
          status: newUser.status || 'active',
          department: newUser.department || '',
          position: newUser.position || '',
          bio: newUser.bio || '',
          avatar: newUser.avatar || '',
          permissions: newUser.permissions || [],
          notifications: newUser.notifications || ['system']
        })
        
        // 设置文件列表
        if (newUser.avatar) {
          fileList.value = [{
            name: 'avatar',
            url: newUser.avatar,
            uid: 'avatar'
          }]
        }
      }
    }, { immediate: true })

    // 监听对话框显示状态，重置表单
    watch(() => props.visible, (visible) => {
      if (visible && props.mode === 'create') {
        resetForm()
      }
    })

    // 重置表单
    const resetForm = () => {
      Object.assign(form, {
        username: '',
        name: '',
        email: '',
        phone: '',
        password: '',
        role: 'agent',
        status: 'active',
        department: '',
        position: '',
        bio: '',
        avatar: '',
        permissions: [],
        notifications: ['system']
      })
      fileList.value = []
      formRef.value?.clearValidate()
    }

    // 文件上传相关方法
    const handleExceed = (files, fileList) => {
      ElMessage.warning('最多只能上传 1 个头像文件')
    }

    const beforeUpload = (file) => {
      const isValidType = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isValidType) {
        ElMessage.error('只能上传 jpg/png/gif 格式的图片!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('上传图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    const handleFileChange = (file, fileList) => {
      if (file.raw) {
        form.avatar = file.raw
      }
    }

    const handleFileRemove = (file, fileList) => {
      form.avatar = ''
    }

    // 提交表单
    const handleSubmit = async () => {
      if (!formRef.value) return

      try {
        await formRef.value.validate()
        submitting.value = true

        // 准备提交数据
        const submitData = {
          ...form,
          avatar: form.avatar instanceof File ? form.avatar : form.avatar
        }

        // 如果是编辑模式，移除密码字段（如果为空）
        if (props.mode === 'edit' && !submitData.password) {
          delete submitData.password
        }

        if (props.mode === 'create') {
          await userStore.createUser(submitData)
          ElMessage.success('用户创建成功！')
        } else {
          await userStore.updateUser(props.user.id, submitData)
          ElMessage.success('用户更新成功！')
        }

        emit('success')
        emit('update:visible', false)
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败：' + (error.message || '未知错误'))
      } finally {
        submitting.value = false
      }
    }

    // 取消操作
    const handleCancel = () => {
      emit('update:visible', false)
    }

    return {
      formRef,
      uploadRef,
      submitting,
      fileList,
      form,
      rules,
      handleExceed,
      beforeUpload,
      handleFileChange,
      handleFileRemove,
      handleSubmit,
      handleCancel
    }
  }
}
</script>

<style scoped>
.permissions-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.permission-group {
  padding: 12px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.permission-group h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.permission-group .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.permission-group .el-checkbox {
  margin-right: 0;
}

.notification-settings {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.notification-settings .el-checkbox-group {
  display: flex;
  gap: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .el-row {
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    margin-bottom: 16px;
  }
  
  .permission-group .el-checkbox-group {
    flex-direction: row;
    flex-wrap: wrap;
  }
  
  .notification-settings .el-checkbox-group {
    flex-direction: column;
    gap: 8px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
}
</style>
